import { useState } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { EyeIcon, EyeSlashIcon } from '@heroicons/react/24/outline'
import { useAuthStore } from '@/stores/authStore'
import { toast } from 'react-hot-toast'


const loginSchema = z.object({
  username: z.string().min(1, '用户名不能为空'),
  password: z.string().min(6, '密码至少6位字符'),
})

type LoginFormData = z.infer<typeof loginSchema>

const LoginPage = () => {
  const [showPassword, setShowPassword] = useState(false)
  const { login, isLoading } = useAuthStore()
  const navigate = useNavigate()
  const location = useLocation()
  
  const from = location.state?.from?.pathname || '/chat'

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<LoginFormData>({
    resolver: zodResolver(loginSchema),
  })

  const onSubmit = async (data: LoginFormData) => {
    try {
      await login(data.username, data.password)
      toast.success('登录成功！')
      navigate(from, { replace: true })
    } catch (error: any) {
      toast.error(error.message || '登录失败，请重试')
    }
  }

  return (
    <>
      <div className="w-full max-w-sm sm:max-w-md mx-auto card-elevated p-8 sm:p-10">
        {/* 登录标题 */}
        <div className="text-center mb-8">
          <div className="mb-4">
            <span className="text-4xl">🌸</span>
          </div>
          <h2 className="text-3xl font-bold text-gradient-primary font-display mb-2">
            登录
          </h2>
        </div>

        <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
          {/* 用户名 */}
          <div className="space-y-2">
            <label htmlFor="username" className="block text-sm font-semibold text-secondary-700">
              用户名
            </label>
            <input
              {...register('username')}
              type="text"
              id="username"
              className={`input-field ${errors.username ? 'border-red-300 focus:border-red-500 focus:ring-red-500' : ''}`}
              placeholder="请输入用户名"
            />
            {errors.username && (
              <p className="mt-1 text-sm text-red-600 flex items-center">
                <span className="mr-1">⚠️</span>
                {errors.username.message}
              </p>
            )}
          </div>

          {/* 密码 */}
          <div className="space-y-2">
            <label htmlFor="password" className="block text-sm font-semibold text-secondary-700">
              密码
            </label>
            <div className="relative">
              <input
                {...register('password')}
                type={showPassword ? 'text' : 'password'}
                id="password"
                className={`input-field pr-12 ${errors.password ? 'border-red-300 focus:border-red-500 focus:ring-red-500' : ''}`}
                placeholder="请输入密码"
              />
              <button
                type="button"
                className="absolute inset-y-0 right-0 pr-4 flex items-center hover:text-primary-600 transition-colors"
                onClick={() => setShowPassword(!showPassword)}
              >
                {showPassword ? (
                  <EyeSlashIcon className="h-5 w-5 text-secondary-400" />
                ) : (
                  <EyeIcon className="h-5 w-5 text-secondary-400" />
                )}
              </button>
            </div>
            {errors.password && (
              <p className="mt-1 text-sm text-red-600 flex items-center">
                <span className="mr-1">⚠️</span>
                {errors.password.message}
              </p>
            )}
          </div>

          {/* 记住我和忘记密码 */}
          <div className="flex items-center justify-between">
            <div className="flex items-center">
              <input
                id="remember-me"
                name="remember-me"
                type="checkbox"
                className="h-4 w-4 text-primary-600 focus:ring-primary-500 border-secondary-300 rounded transition-colors"
              />
              <label htmlFor="remember-me" className="ml-2 block text-sm text-secondary-700 font-medium">
                记住我
              </label>
            </div>

            {/* 忘记密码入口已隐藏 */}
          </div>

          {/* 登录按钮 */}
          <button
            type="submit"
            disabled={isLoading}
            className="btn-primary w-full h-12 text-base font-semibold"
          >
            {isLoading ? (
              <div className="flex items-center justify-center space-x-2">
                <div className="loading-spinner w-5 h-5"></div>
                <span>登录中...</span>
              </div>
            ) : (
              '登录'
            )}
          </button>
        </form>

        {/* 底部装饰 */}
        <div className="mt-8 text-center">
          <div className="w-16 h-px bg-gradient-to-r from-transparent via-primary-300 to-transparent mx-auto"></div>
        </div>
      </div>
    </>
  )
}

export default LoginPage